package com.agent.history.service.Impl;

import com.agent.commons.exception.BaseException;
import com.agent.commons.other.MessageHistory;
import com.agent.commons.utils.JacksonUtil;
import com.agent.feign.client.UserClient;
import com.agent.history.dataobject.ConversationBaseDO;
import com.agent.history.mapper.ConversationMapper;
import com.agent.history.service.ConversationService;
import com.agent.history.vo.ConversationListVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.agent.commons.constants.RedisConstants.MESSAGE_HISTORY;

@Service
@Slf4j
public class ConversationServiceImpl implements ConversationService {
    @Resource
    private ConversationMapper conversationMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserClient userClient;
    @Override
    public void addConversation(MessageHistory messageHistory) {
        int i = conversationMapper.addConversation(messageHistory);
        if(i==0){
            log.error("添加会话失败!");
            throw new BaseException(108,"添加会话失败!");
        }
    }

    /**
     * 校验会话id和用户id是否匹配
     * @param userId
     * @param conversationId
     * @return
     */
    @Override
    public boolean checkConversationIdWithUserId(String userId, String conversationId) {
        //如果查找结果不为0，则代表匹配,返回true
        return conversationMapper.checkConversationIdWithUserId(userId,conversationId)!=0;
    }

    /**
     * 获取用户会话列表
     * @param userId
     * @return
     */
    @Override
    public List<ConversationBaseDO> getConversationMember(String userId) {
        return conversationMapper.getConversationMember(userId);
    }

    /**
     * 从Redis中获取会话Id
     * @param userId
     * @return
     */
    @Override
    public List<ConversationListVO> getConversationListVOFromRedis(String userId){
        //获取所有的会话列表
        Set<String> range = stringRedisTemplate.opsForZSet().range(MESSAGE_HISTORY + userId, 0, -1);
        //如果为空，则返回空集合
        if(range==null){
            log.error("用户没有会话记录！");
            return new ArrayList<>();
        }
        //不为空则获取根据会话id从Redis中获取数据
        List<ConversationListVO> list = new ArrayList<>();
        //遍历会话id集合
        for (String s : range) {
            ConversationListVO conversationListVO = JacksonUtil.readValue(s, ConversationListVO.class);
            list.add(conversationListVO);
        }
        return list;
    }

    /**
     * 用户是否存在
     * @param userId
     * @return
     */
    @Override
    public boolean checkUserExist(String userId) {
        return userClient.getMember(userId)!=null;
    }
}
